
import ala from 'ala'
import admin from 'admin'

/*
* 拖动排序 
*/
export function sort (array, newIndex, oldIndex) {
  if (!array) {
    array = []
  }
  var allArray = ala.arrayDeepAll(array)
  var currentRow = allArray.splice(oldIndex, 1)[0]
  var endRow = allArray.splice(newIndex, 1)[0]
  if (!endRow) {
    endRow = allArray.splice(newIndex - 1, 1)[0]
  }
  if (currentRow.children && currentRow.children.length > 0 && endRow.level === 3) {
    ala.error('三级分类中，不能拖入有子菜单的分类')
    return null
  }

  if (endRow.level === 2) {
    if (currentRow.children) {
      var hasChild = false
      for (var i = 0; i < currentRow.children.length; i++) {
        var element = currentRow.children[i]
        if (element.children && element.children.length > 0) {
          hasChild = true
          break
        }
      }
      if (hasChild === true) {
        ala.error('二级分类中，不能拖入有子三级菜单的分类')
        return null
      }
    }
  }

  // 排序
  array = ala.arrayDeepSort(array, newIndex, oldIndex)

  setTimeout(async () => {
    var response = await admin.relationSort(array)
    if (response) {
      ala.toast('保存成功')
    }
  }, 100)
  return array
}

